package com.lxf.cn.uitl.export;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.util.ResourceUtils;

import java.io.IOException;

/**
 * Created by liaoxuefeng on 2018/11/26.
 */
public class ExportExcelUtil {
    /**
     *
     * @param templatePath
     * @param datas
     * @param headers
     * @return
     */
    public static XSSFWorkbook genInputStream(String templatePath, JSONArray datas, String[] headers) {
        XSSFWorkbook wb=null;
        try {
            wb = (XSSFWorkbook) WorkbookFactory.create(ResourceUtils.getFile("classpath:"+templatePath));
            XSSFSheet sheet = wb.getSheetAt(0);
            XSSFRow row;
            XSSFCell cell;

            XSSFCellStyle style = wb.createCellStyle();           // 样式对象
            style.setVerticalAlignment(VerticalAlignment.CENTER);  // 垂直
            style.setAlignment(HorizontalAlignment.CENTER);             // 水平
            style.setBorderBottom(BorderStyle.THIN); //下边框
            style.setBorderLeft(BorderStyle.THIN);//左边框
            style.setBorderTop(BorderStyle.THIN);//上边框
            style.setBorderRight(BorderStyle.THIN);//右边框

            // 产生表格标题行
            row = sheet.createRow(0);
            for (short i = 0;  i < headers.length; i++ )
            {
                cell = row.createCell(i);
                cell.setCellStyle(style);
                cell.setCellValue(headers[i]);
            }

            //设置数据
            String [] header = new String[]{"userName" };
            for(int i = 0 , j = 0  ;i < datas.size() ; i++ , j++){
                row = sheet.createRow(i + 1);
                JSONObject rowObject = datas.getJSONObject(j);
                for(int k =0 ;k < headers.length;k++){
                    cell = row.createCell(k);
                    cell.setCellValue(rowObject.getString(header[k]));
                    cell.setCellStyle(style);
                }
            }
        } catch (IOException e) {
            throw  new RuntimeException("导出文件失败");
        } catch (InvalidFormatException e) {
            throw  new RuntimeException("导出文件失败");
        }
        return wb;
    }
}
